#!/usr/bin/env python
# coding: utf-8
import cv2
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
from xml.dom.minidom import parse
import pytesseract
import os

print("温馨提示：本机为", os.cpu_count(), "核CPU")
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
tessdata_dir_config = '--tessdata-dir "c:\\Program Files\\Tesseract-OCR\\tessdata" --psm 6'


# 利用四个顶点的横纵坐标存在极值的关系

def contour_points(img):
    img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    img_gray = cv2.dilate(img_gray, None)
    # 焦点检测必须是float32
    img_gray = np.float32(img_gray)
    # 角点检测
    dst = cv2.cornerHarris(img_gray, 2, 3, 0.04)
    # dst = cv2.dilate(dst, (7, 7))
    # 角点检测可视化检验
    #     img_jiaodian = img
    #     img_jiaodian[dst>0.001*dst.max()]=[0,0,255]
    #     cv2.imwrite("C:\\Users\\lg\\Desktop\\form_ocr_excel\\hand write\\numbers_jiaodian.jpg", img_jiaodian)
    # np.where 返回一个元组，其中两个列表，分别为横纵坐标
    xy_points = np.where(dst > 0.0001 * dst.max())
    # print(dst > 0.001 * dst.max())
    # print(xy_points)
    # 筛选轮廓四个角点
    # 其中x : row   y :col
    l_ru = 50

    l_lu = 200

    l_rd = 200

    l_ld = 200

    x_min = min(xy_points[0])
    x_max = max(xy_points[0])
    y_min = min(xy_points[1])
    y_max = max(xy_points[1])
    # print(x_min, x_max, y_min, y_max)

    for i in range(len(xy_points[0])):
        # print(contours[0][i][0][0],contours[0][i][0][1])
        x = xy_points[0][i] - x_min
        y = xy_points[1][i] - y_min
        l1 = sqrt(x ** 2 + y ** 2)
        if (l1 < l_ru):
            #             x_ru_m = x
            #             y_ru_m = y
            l_ru = l1
            x_left_up = xy_points[0][i]
            y_left_up = xy_points[1][i]

        x = x_max - xy_points[0][i]
        y = xy_points[1][i] - y_min
        l2 = sqrt(x ** 2 + y ** 2)
        if (l2 < l_lu):
            l_lu = l2
            x_left_d = xy_points[0][i]
            y_left_d = xy_points[1][i]

        x = xy_points[0][i] - x_min
        y = y_max - xy_points[1][i]
        l3 = sqrt(x ** 2 + y ** 2)
        if (l3 < l_ld):
            l_ld = l3
            x_right_up = xy_points[0][i]
            y_right_up = xy_points[1][i]

        x = x_max - xy_points[0][i]
        y = y_max - xy_points[1][i]
        l4 = sqrt(x ** 2 + y ** 2)
        if (l4 < l_rd):
            l_rd = l4
            x_right_down = xy_points[0][i]
            y_right_down = xy_points[1][i]
            # print(x_right_d)

    return ([[x_left_up, y_left_up], [x_right_up, y_right_up], [x_left_d, y_left_d], [x_right_down, y_right_down]])


def xml_read(xml_read_path):
    Index = 0
    # XML文件的读取
    dom = parse(xml_read_path)
    # 获取文档元素对象
    data = dom.documentElement
    # 读取sheet
    sheet = data.getElementsByTagName('Worksheet')
    # 读取 table
    table = sheet[0].getElementsByTagName('Table')
    # 读取table中的默认参数
    # 默认行高 
    de_height = float(table[0].getAttribute("ss:DefaultRowHeight"))
    # 默认列宽
    de_width = float(table[0].getAttribute("ss:DefaultColumnWidth"))
    # 默认行数
    row_num = int(table[0].getAttribute("ss:ExpandedRowCount"))
    # 默认列数
    col_num = int(table[0].getAttribute("ss:ExpandedColumnCount"))
    # 读取列宽
    # Column = table[0].getElementsByTagName('Column')
    # 读取列宽
    # 首先读取所有的列宽元素
    Column = table[0].getElementsByTagName('Column')
    col_list = col_num * [de_width]
    # 列宽元素的索引
    i = 0
    for col in Column:
        if (col.getAttribute("ss:Span") != '' and col.getAttribute("ss:Index") != ''):
            index = int(col.getAttribute("ss:Index"))
            span = int(col.getAttribute("ss:Span"))
            width = float(col.getAttribute("ss:Width"))
            col_list[index - 1:index + span] = [width] * (span + 1)
            i = index + span
        elif (col.getAttribute("ss:Span") == '' and col.getAttribute("ss:Index") != ''):
            index = int(col.getAttribute("ss:Index"))
            width = float(col.getAttribute("ss:Width"))
            col_list[index - 1] = width
            i = index
        elif (col.getAttribute("ss:Span") == '' and col.getAttribute("ss:Index") == ''):
            width = float(col.getAttribute("ss:Width"))
            col_list[i] = width
            i = i + 1
            # print(width, i)

    # 读取所有的行信息
    Rows = table[0].getElementsByTagName('Row')
    # 读取每一行行高
    height_list = []
    for row in Rows:
        # height_list.append(float(row.getAttribute("ss:Height")))
        if (row.getAttribute("ss:Height") == ''):
            height_list.append(float(de_height))
        else:
            height_list.append(float(row.getAttribute("ss:Height")))

    # 以左上顶点为原点，各个单元的位置关系,向下、向右为正方向
    All_cell_points = []
    # 坐标的行列信息【【cell_col, cell_row】, ...】,为后续的表格写入做准备
    cells_adress = []
    cell_col = []
    cell_row = []
    # 同时获取表格的结构信息
    for index in range(len(Rows)):
        # 获取每一行中的单元格并计算
        cells = Rows[index].getElementsByTagName('Cell')
        #     print()
        #     print(index+1,'行：')

        # i : cell索引
        i = 0
        cell_col = []
        cell_row = []

        # 按行记录每个单元格的位置信息
        row_cell_points = []
        for index_cell, cell in enumerate(cells):
            # print('每行的单元格的次序：',index_cell+1)
            # print()
            # 计算得到单元格的起始单元格位置
            # 计算列宽
            #  ss:Index 一般是合并单元格从第一个开始就会出现ss:Index或者是某个纵向合并单元格之后多行的合并单元格
            # ，其后面的数字是在原本一个的基础上又合并的单元格数量

            # 这是该行的第一个单元格不是从最边上开始的且不是合并单元格
            if (cell.getAttribute("ss:Index") and cell.getAttribute('ss:MergeAcross') == ''):
                # print("ss:Index:")
                cell_col = []
                cell_row = []
                i = int(cell.getAttribute("ss:Index")) - 1
                cell_col.append(i)
                width = col_list[i]
                width_start = sum(col_list[:i])
                width_end = width + width_start

                cell_width = [width_start, width_end]
                # print('width:',cell_width)
                i = i + 1
                cell_col.append(i)

            # 合并单元格的数量和方向
            # MergeAcross横向合并，其后面的数字是在原来一个的基础上合并了单元格的数量
            # #这是该行的第一个单元格不是从最边上开始的而且是合并单元格
            elif (cell.getAttribute("ss:Index") and cell.getAttribute('ss:MergeAcross')):
                # print("ss:Index:ss::Merge")
                cell_col = []
                cell_row = []
                i = i + int(cell.getAttribute("ss:Index")) - 1
                merge_col = int(cell.getAttribute("ss:MergeAcross"))
                cell_col.append(i)
                width = sum(col_list[i:i + merge_col + 1])
                width_start = sum(col_list[:i])
                width_end = width + width_start
                cell_width = [width_start, width_end]
                # print('width:',cell_width)

                cell_col.append(i)
                i = i + merge_col + 1
                cell_col.append(i)
            # 按照正常顺序合并的单元格
            elif (cell.getAttribute("ss:MergeAcross")):
                # print("ss:MergeAcross:")
                cell_col = []
                cell_row = []
                merge_col = int(cell.getAttribute("ss:MergeAcross"))
                # 存放每个单元格起始和结束的位置
                width = sum(col_list[i:i + merge_col + 1])
                width_start = sum(col_list[:i])
                width_end = width + width_start
                cell_width = [width_start, width_end]

                # print('width:',cell_width)

                cell_col.append(i)
                i = i + merge_col + 1
                cell_col.append(i)



            # 正常的单元格
            elif (cell.getAttribute("ss:Index") == '' and cell.getAttribute("ss:MergeAcross") == ''):
                # print("ss:IN ss:m ==   ")
                cell_col = []
                cell_row = []

                # print(i)

                width = col_list[i]
                cell_col.append(i)
                width_start = sum(col_list[:i])
                width_end = width + width_start
                cell_width = [width_start, width_end]

                # print('width:',cell_width)

                i = i + 1
                cell_col.append(i)

            # 计算单元格的行高
            if (cell.getAttribute("ss:MergeDown")):
                merge_row = int(cell.getAttribute("ss:MergeDown"))
                height = sum(height_list[index:index + merge_row + 1])
                height_start = sum(height_list[:index])
                height_end = height_start + height
                cell_height = [height_start, height_end]

                # print('height:',cell_height)

                cell_row.append(index)
                cell_row.append(index + merge_row + 1)

            elif (cell.getAttribute("ss:MergeDown") == ''):
                height_start = sum(height_list[:index])
                height = height_list[index]
                height_end = height_start + height
                cell_height = [height_start, height_end]

                #  print('height:',cell_height)

                cell_row.append(index)
                cell_row.append(index + 1)

            # 存放单元格左上和右下角点的坐标
            cell_points = [[height_start, width_start], [height_end, width_end], Index]

            row_cell_points.append(cell_points)

            # 存放每个单元格的行列位置信息
            cells_adress.append([cell_col, cell_row])

            Index = Index + 1

        All_cell_points.append(row_cell_points)

    return All_cell_points, Rows, sum(col_list), sum(height_list)


def Real_cell_points(All_cell_points, col_table, height_table, x_origin, y_origin):
    real_points = []

    for rows in All_cell_points:
        row_points = []
        if len(rows) != 0:
            for cell_points in rows:
                x_start = int(cell_points[0][0] / height_table * real_row) + x_origin
                x_end = int(cell_points[1][0] / height_table * real_row) + x_origin

                y_start = int(cell_points[0][1] / col_table * real_col) + y_origin
                y_end = int(cell_points[1][1] / col_table * real_col) + y_origin

                row_points.append([x_start, x_end, y_start, y_end])

            real_points.append(row_points)
        else:
            real_points.append([])

    return real_points


def shice_record(Rows):
    record = []

    for index_row in range(len(Rows)):

        # 获取每一行中的单元格并计算
        cells = Rows[index_row].getElementsByTagName('Cell')

        for index_cell, cell in enumerate(cells):

            data = cell.getElementsByTagName('Data')

            if (len(data)):

                value = data[0].childNodes[0].data
                if ("实测" in value):
                    print('yes')
                    print(value)

                    if (cell.getAttribute("ss:MergeDown") == ''):
                        num_row_measure = 1

                    else:
                        num_row_measure = int(cell.getAttribute("ss:MergeDown"))

                    record.append([All_cell_points[index_row][index_cell], [index_row, index_cell, num_row_measure]])

    return record


# 对All_cell_points筛选以及重新排序

def takeElementDixian(l):
    return l[0][0][1][0]


def takeElementLeftlow(l):
    return l[0][0][1]


# 对All_cell_points筛选以及重新排序

def sort_All_cell_points(All_cell_points):
    # 以单元格的底线为基准
    # 收集所有单元格的底线值
    low_cell_pre = 0
    low_cell_list = []
    for row in All_cell_points:
        for cell in row:
            low_cell = cell[1][0]
            # print(cell)
            if (low_cell in low_cell_list):
                continue
            low_cell_list.append(low_cell)

    All_cell_low = []
    for low in low_cell_list:

        cells = []
        # 遍历所有的单元格寻找底线相同的单元格
        index = 0

        for index_row, row in enumerate(All_cell_points):

            for index_cell, cell in enumerate(row):

                # print(cell)
                if (cell == []):
                    continue

                low_cell = cell[1][0]

                if (low_cell == low):
                    cells.append([cell, [index_row, index_cell], index])
                index = index + 1

        All_cell_low.append(cells)

    All_cell_low.sort(key=takeElementDixian)
    l = []
    for cells in All_cell_low:
        cells.sort(key=takeElementLeftlow)
        l.append(cells)
    All_cell_low = l
    return All_cell_low




def shice_class(record):
    # 将“实测”分类
    # 上下挨着的“实测”即为同一“标准”下的待检测实测值；不挨着的即不同的标准值；
    # “挨着”衡量标准：待分类的单元格的左上角点和右上角点的位置与上一个单元格的左下角点和右下角点的位置相同。
    point_ll = []
    point_rl = []
    l = []
    # 存放拥有相同标准值的待检测实测值
    shice_list = []
    for shice_record in record:

        shice_cell_point = shice_record[0]
        # 计算待分类单元格的上面两个角点
        shice_point_lu = shice_cell_point[0]
        shice_point_ru = [shice_cell_point[0][0], shice_cell_point[1][1]]

        if (point_ll == shice_point_lu and point_rl == shice_point_ru):
            l.append(shice_record)
        else:
            if (l != []):
                shice_list.append(l)
            l = []
            l.append(shice_record)
        if (record.index(shice_record) == len(record) - 1):
            shice_list.append(l)
        point_ll = [shice_cell_point[1][0], shice_cell_point[0][1]]
        point_rl = shice_cell_point[1]

    return shice_list



def shice_testAgain(Rows, shice_list):
    # 对筛选出来的“实测”进一步判断
    record_biaozhun = []

    record_saixuan = []

    for shice_same_list in shice_list:

        shice_record = shice_same_list[0]
        shice_cell_points = shice_record[0]
        # print(shice_cell_points)
        # 计算出上面相邻的单元格右角点的坐标值
        shice_pre_rl = [shice_cell_points[0][0], shice_cell_points[1][1]]

        # 遍历一遍所有的单元格找出“实测”上面一个单元格
        for i in range(len(All_cell_low)):

            for cell in All_cell_low[i]:
                # 找出单元格与该右角点值相等的单元格
                if (shice_pre_rl in cell[0] and cell[0].index(shice_pre_rl) == 1):

                    cell_jiance = Rows[cell[1][0]].getElementsByTagName('Cell')[cell[1][1]]
                    data = cell_jiance.getElementsByTagName('Data')
                    value = data[0].childNodes[0].data

                    if ("标准" in value or "Sample"):
                        record_saixuan.append(shice_same_list)
                        record_biaozhun.append(cell)

    return record_biaozhun, record_saixuan


# In[ ]:


# In[10]:


def biaozhun_cells(All_cell_low, record_biaozhun):
    # 根据“标准”单元格作为起始点，进一步计算出需要标准的列数
    # 具体，首先将与“标准”单元格底线值相同的所有单元格取出来，之后再根据单元格之间的连续性判断是否为标准

    for record in record_biaozhun:

        low_biaozhun = record[0][1][0]

        # 存放与“标准”相同单元格底线的在All_cell_low中的索引
        index_low = []

        for index, low_points in enumerate(All_cell_low):

            # print(low_points)
            if (low_biaozhun == low_points[0][0][1][0]):
                index_low.append(index)

                break

    # 对所有与“标准”单元格底线相同的待选单元格进行判断
    # 判断标准：连续性：待检测单元格的左下角点与前一个单元格的右下角点相同  包含：待检单元格高度小于“标准”单元格的高度  
    # 单元格内容：数字、大于、小于号 -

    # 存放前一个单元格的右下角点以及“标准”单元格的高度
    point_height = [[], 0]
    # 存放 “标准值”的单元格索引
    biaozhun_index = []
    for index, record in enumerate(record_biaozhun):

        point_height[0] = record[0][1]

        point_height[1] = record[0][1][0] - record[0][0][0]

        print(point_height[0])
        cells = All_cell_low[index_low[index]]

        index_list = []
        for cell in cells:
            # print(cell)
            # 计算待测单元格的左下角点坐标以及其单元格高度
            point_LeftLow = [cell[0][1][0], cell[0][0][1]]
            cell_height = cell[0][1][0] - cell[0][0][0]

            cell_jiance = Rows[cell[1][0]].getElementsByTagName('Cell')[cell[1][1]]
            data = cell_jiance.getElementsByTagName('Data')
            value = data[0].childNodes[0].data

            flag = 0
            # print(value, cell[1])
            # 判断是否连续、是否包含
            if (point_LeftLow == point_height[0] and cell_height <= point_height[1]):

                # 在连续和包含的基础上判断单元格中的内容
                value = list(value)

                if ("≤" in value or "≥" in value):
                    flag = 1
                if ("-" in value):
                    if ('0' in value or '1' in value or '2' in value or '3' in value
                            or '4' in value or '5' in value or '6' in value or '7' in value or '8' in value or '9' in value):
                        flag = 1

                if (flag == 1):
                    print(value)
                    print(cell)
                    # index_list 中第一个元素为在All_cell_low中的索引，第二个元素是为单元格横线的起点、终点， 第三个元素为单元格数量的索引
                    index_list.append([cell[1], [cell[0][0][1], cell[0][1][1]], cell[0][2]])

                point_height[0] = cell[0][1]

                point_height[1] = cell[0][1][0] - cell[0][0][0]

                # print(value)

        biaozhun_index.append(index_list)

    return biaozhun_index



def num_shice(start_record, All_cell_low, biaozhun_index):
    records = start_record
    # 存放前一个单元格的右下角点以及“实测”单元格的高度
    point_height = 0
    # 存放 “实测”的单元格索引
    shice_index = []

    for index_record, record_list in enumerate(records):

        # biaozhun_num = len(biaozhun_index[index_record])

        # 获得标准值的横线列表
        biaozhun_hengxian_list = [x[1] for x in biaozhun_index[index_record]]

        # record_list : 拥有相同标准值的“实测”

        # 找出所有在“实测单元格”范围之内的所有的单元格，即单元格的底线在单元格顶线、底线在“实测”顶线、底线之内
        # 对同一“标准值”的实测值进行筛选

        up_shice = record_list[0][0][0][0]
        low_shice = record_list[-1][0][1][0]
        print("一组实测 ：", up_shice, low_shice)
        index_low = []

        for i, low_points in enumerate(All_cell_low):

            for low_point in low_points:

                # print(low_point)

                if (low_point[0][1][0] <= low_shice and low_point[0][0][0] >= up_shice):
                    index_low.append(i)

                    # break

        index_low = list(set(index_low))
        print(index_low)

        shice_l = []

        for record in record_list:

            # 同一“标准”下的“实测”的高度
            point_height = record_list[-1][0][1][0] - record_list[0][0][0][0]

            # 一个“实测”下的实测值
            point_low_line = record[0][1][0]
            point_up_line = record[0][0][0]

            # 将符合“实测”的单元格聚集
            cells = []
            for index in index_low:
                cell = All_cell_low[index]
                cells = cells + cell
                # cells = All_cell_low[index_low[index]]

                index_list = []
            # print(cell)
            for cell in cells:
                flag_hengxian = 0
                # print(cell)
                # 计算待测单元格的顶线、底线高度以及其单元格高度
                cell_up_line = cell[0][0][0]
                cell_low_line = cell[0][1][0]
                cell_height = cell[0][1][0] - cell[0][0][0]

                # print("cell_height:", cell_height)
                cell_jiance = Rows[cell[1][0]].getElementsByTagName('Cell')[cell[1][1]]
                data = cell_jiance.getElementsByTagName('Data')
                value = data[0].childNodes[0].data
                # print("cell:",cell)
                # print(value, cell[1])

                # 单元格横线的坐标
                point_hengxian = [cell[0][0][1], cell[0][1][1]]
                if (point_hengxian in biaozhun_hengxian_list):
                    flag_hengxian = 1
                    biaozhun_index_list = biaozhun_hengxian_list.index(point_hengxian)

                if (
                        flag_hengxian and cell_height <= point_height and cell_low_line <= point_low_line and cell_low_line > point_up_line):
                    # print(value)
                    #                     print("point_low_line:",point_low_line, "point_up_line", point_up_line)
                    #                     print(cell_low_line)
                    l = [cell[1], cell[0][2], biaozhun_index_list]
                    index_list.append(l)

                # print(value)
            shice_l.append(index_list)

        shice_index.append(shice_l)

    return shice_index




# 对“标准” 和“实测”单元格进行识别，生成对应的数据
def distinguish(shice_list, biaozhun_list, FilePath):
    shice = []
    biaozhun = []
    img_read = cv2.imread
    image_to_string = pytesseract.image_to_string

    for i in range(len(biaozhun_list)):

        biaozhun_index = [x[-1] for x in biaozhun_list[i]]
        biaozhun_l = []
        for index in biaozhun_index:
            img = img_read(FilePath + str(index) + '.jpg')

            text = image_to_string(img, lang="1214", config=tessdata_dir_config)
            text = text.replace(' ', '')
            biaozhun_l.append(text[0:-2])
        biaozhun.append(biaozhun_l)

        l_shice = []
        for index_list in shice_list[i]:

            shice_list_samebiaozhun = [x[1] for x in index_list]
            shice_biaozhun_index = [x[-1] for x in index_list]
            index_cell_points = [x[0] for x in index_list]
            shice_l = []
            for m, shice_index in enumerate(shice_list_samebiaozhun):
                img = img_read(FilePath + str(shice_index) + '.jpg')
                text = image_to_string(img, lang='font2', config=tessdata_dir_config)
                text = text.replace(' ', '')
                print(text[0:-2])
                shice_l.append([text[0:-2], shice_biaozhun_index[m], index_cell_points[m]])
            l_shice.append(shice_l)

        shice.append(l_shice)

    return shice, biaozhun



def draw_mask(img, box, color):
    # box = [xl, yl, xr, yr]
    zeros = np.zeros((img.shape), dtype=np.uint8)
    if (color == 1):  # 颜色为绿色，即合格

        zeros_mask = cv2.rectangle(zeros, (box[0], box[1]), (box[2], box[3]),
                                   color=(0, 255, 0), thickness=-1)  # thickness=-1 表示矩形框内颜色填充
    else:
        zeros_mask = cv2.rectangle(zeros, (box[0], box[1]), (box[2], box[3]),
                                   color=(0, 0, 255), thickness=-1)  # thickness=-1 表示矩形框内颜色填充
    # 透明度 
    alpha = 0.8
    beta = 0.8

    mask_img = cv2.addWeighted(img, alpha, zeros_mask, beta, 0)

    return mask_img


# maks函数测试

# img = img_jiaozheng[1709:1866, 1526:1814 ]
# # img = cv2.imread("H:\\20201111_dqform\\test\\0003\\assess_roi\\25.jpg")
# box = [0, 0, 301, 157 ]
# color = 1
# mask = draw_mask(img, box, color)
# plt.imshow(mask)


# 根据标准中的字符串确定标准范围
# 根据标准范围对实测进行评估
# 输出结果反应在图像中，合格为绿色，不合格标红
def assess(biaozhun_list, shice_list, real_cell_points, img_jiaozheng):
    for standard_index, value_measured_class in enumerate(shice_list):

        standard_list = biaozhun_list[standard_index]

        for value_measured_list in value_measured_class:
            # 颜色标志点
            color = 0
            for value_measured in value_measured_list:

                if ('/' in list(value_measured[0])):
                    break

                value_StandardIndex = value_measured[1]
                # 每个单元格的图像中的真实位置
                real_points = real_cell_points[value_measured[-1][0]][value_measured[-1][1]]
                cell_img = img_jiaozheng[real_points[0]:real_points[1], real_points[2]:real_points[3]]
                #                 x_center = int ((real_points[0] + real_points[1]) / 2)
                #                 y_center = int((real_points[2] + real_points[3]) 2 )
                h_cell = int(real_points[1] - real_points[0])
                w_cell = int(real_points[3] - real_points[2])
                box_xl = int(w_cell / 5)
                box_yl = int(h_cell / 5)
                box_xr = int(w_cell / 5 * 4)
                box_yr = int(h_cell / 5 * 4)
                box = [box_xl, box_yl, box_xr, box_yr]

                print('real_points:', real_points)

                value_measured = float(value_measured[0])

                value_standard = standard_list[value_StandardIndex]

                print("value_measured:", value_measured)
                print("value_standard:", value_standard)
                if ("≥" in value_standard):
                    value_standard = value_standard.replace('≥', '')
                    value_standard = float(value_standard)

                    if (value_measured >= value_standard):
                        print("合格！")
                        color = 1


                    else:
                        print("不合格！")
                elif ("≤" in value_standard):

                    value_standard = value_standard.replace('≤', '')
                    value_standard = float(value_standard)

                    if (value_measured <= value_standard):
                        print("合格！")
                        color = 1
                    else:
                        print("不合格！")

                elif ("-" in value_standard):

                    value_standard = list(value_standard)
                    print(value_standard)
                    i = value_standard.index("-")
                    value_standard_start = float(''.join(value_standard[:i]))
                    value_standard_end = float(''.join(value_standard[i + 1:]))
                    if (value_measured >= value_standard_start and value_measured <= value_standard_end):
                        print("合格！")
                        color = 1
                    else:
                        print("不合格！")
                print("box:", box)
                print(cell_img.shape)
                mask_img = draw_mask(cell_img, box, color)
                img_jiaozheng[real_points[0]:real_points[1], real_points[2]:real_points[3]] = mask_img
                # plt.imshow(mask_img)

    return img_jiaozheng


def execel_information(Rows, All_cell_points):
    record_information = []

    for index_row in range(len(Rows)):

        # 获取每一行中的单元格并计算
        cells = Rows[index_row].getElementsByTagName('Cell')
        num_cells = len(cells)
        information = []
        for index_cell, cell in enumerate(cells):

            data = cell.getElementsByTagName('Data')

            if (len(data)):

                value = data[0].childNodes[0].data

                if ("报告编号" in value or '结论' in value or '审核' in value
                        or '校对' in value or "验收标准" in value or "试验员" in value):
                    # print('yes')
                    print(value)
                    # 返回“报告编号”， 及其图像中真实的坐标值， 以及其所对应内容的图像中真实的坐标值
                    information.append([value, [All_cell_points[index_row][index_cell], [index_row, index_cell]],
                                        [All_cell_points[index_row][index_cell + 1], [index_row, index_cell + 1]]])
                    record_information.append([value, [All_cell_points[index_row][index_cell], [index_row, index_cell]],
                                               [All_cell_points[index_row][index_cell + 1],
                                                [index_row, index_cell + 1]]])

    return record_information


# In[ ]:


# In[ ]:


# In[ ]:


# In[148]:


excel_information = execel_information(Rows, All_cell_points)

# In[149]:


excel_information[0][1][-1]

# In[150]:


excel_information[1][-1][0][-1]

# In[151]:


file_jiaozheng = 'H:\\20201111_dqform\\test\\0002\\binary_cell_roi\\'


# In[152]:


def get_information(excel_information, file_jiaozheng):
    img_read = cv2.imread
    image_to_string = pytesseract.image_to_string
    information = []
    for index_information in excel_information:
        index_img = index_information[-1][0][-1]
        print(index_img)
        value = index_information[0]
        img = img_read(file_jiaozheng + str(index_img) + '.jpg')
        print(file_jiaozheng + str(index_img) + '.jpg')
        text = image_to_string(img, lang="font2", config=tessdata_dir_config)
        text = text.replace(' ', '')
        value = value.replace(' ', '')
        text = text[0:-2].replace('\n', '')
        # text = value + ' : '+str(text)
        information.append([value, text])
    return information


# In[154]:


excel_distinguished_information = get_information(excel_information, file_jiaozheng)

# In[155]:


excel_distinguished_information


# In[ ]:


# In[ ]:


# In[ ]:


# In[156]:


def mask_information(real_cell_points, excel_information, excel_distinguished_information, img_jiaozheng):
    color = 0
    for index, excel in enumerate(excel_information):
        print(excel)
        if ('报告编号' in excel[0] and excel_distinguished_information[index][1] != ''):
            color = 1
        if ('试验员' in excel[0] and excel_distinguished_information[index][1] != ''):
            color = 1
        if ('验收标准' in excel[0] and excel_distinguished_information[index][1] != ''):
            color = 1
        if ('结论' in excel[0] and excel_distinguished_information[index][1] == '合格'):
            color = 1
        if ('校对' in excel[0] and excel_distinguished_information[index][1] == ''):
            color = 1
        if ('审核' in excel[0] and excel_distinguished_information[index][1] == ''):
            color = 1
        for cell in excel[1:]:
            real_points = real_cell_points[cell[-1][0]][cell[-1][1]]
            cell_img = img_jiaozheng[real_points[0]:real_points[1], real_points[2]:real_points[3]]
            print(cell_img.shape)
            h_cell = int(real_points[1] - real_points[0])
            w_cell = int(real_points[3] - real_points[2])
            box_xl = int(w_cell / 5)
            box_yl = int(h_cell / 5)
            box_xr = int(w_cell / 5 * 4)
            box_yr = int(h_cell / 5 * 4)
            box = [box_xl, box_yl, box_xr, box_yr]
            mask_img = draw_mask(cell_img, box, color)
            img_jiaozheng[real_points[0]:real_points[1], real_points[2]:real_points[3]] = mask_img


# In[160]:


img_jiaozheng = cv2.imread("H:\\20201111_dqform\\test\\0002\\0002_assessed.png")
mask_information(real_cell_points, excel_information, excel_distinguished_information, img_jiaozheng)

# In[161]:


plt.imshow(img_jiaozheng)

# In[162]:


cv2.imwrite("H:\\20201111_dqform\\test\\0002\\excel_assessed.png", img_jiaozheng)

# In[ ]:


# In[16]:


# 评估程序整合


# In[18]:


xml_read_path = "H:\\20201111_dqform\\test\\0002\\0002.xml"

# 获得表格所有单元格的位置信息,以及表格行信息

All_cell_points, Rows, col_table, height_table = xml_read(xml_read_path)

# record[0] :实测单元格的信息 
# record[0][0] : 【右上角点， 左下角点，单元格数索引】
# record[0][1] : 在All_cell_points中的索引以及合并单元格数量-1
# 获得“实测”单元格的信息
record = shice_record(Rows)

# 对所有的单元格的信息进行横向和纵向排序
All_cell_low = sort_All_cell_points(All_cell_points)

img_jiaozheng = cv2.imread("H:\\20201111_dqform\\test\\0002\\0002_jiaozheng.png")
contuors_jiaozheng_points = contour_points(img_jiaozheng)
x_origin, y_origin = contuors_jiaozheng_points[0]

# 计算得到表格的总宽、总高的像素值，结合原点对电子表格解析得到的宽高信息转化为像素值
real_col = ((contuors_jiaozheng_points[3][1] - contuors_jiaozheng_points[2][1]) + (
            contuors_jiaozheng_points[1][1] - contuors_jiaozheng_points[0][1])) / 2
real_row = ((contuors_jiaozheng_points[3][0] - contuors_jiaozheng_points[1][0]) + (
            contuors_jiaozheng_points[2][0] - contuors_jiaozheng_points[0][0])) / 2

# 得到每个单元格在图像中的真实位置坐标
real_cell_points = Real_cell_points(All_cell_points, col_table, height_table, x_origin, y_origin)

# 对实测单元格进行分类，同一类的单元格的拥有相同的“标准值”
shice_list = shice_class(record)

# 对“实测”进行进一步筛选，以及找出属于其的“标准”
record_biaozhun, record_saixuan = shice_testAgain(Rows, shice_list)

# 找出每组实测值要进行对比的“标准值”
biaozhun_list = biaozhun_cells(All_cell_low, record_biaozhun)

# 找出所有要进行评估的“实测值”
shice_list = num_shice(record_saixuan, All_cell_low, biaozhun_list)




FilePath = 'H:\\20201111_dqform\\test\\0002\\0002_roi_accessed\\'
shice, biaozhun = distinguish(shice_list, biaozhun_list, FilePath)

# In[ ]:


# In[23]:


img = assess(biaozhun, shice, real_cell_points, img_jiaozheng)
cv2.imwrite("H:\\20201111_dqform\\test\\0002\\0002_assessed.png", img)

# In[ ]:


# In[16]:


shice_list

# In[17]:


biaozhun_list

# In[ ]:


# In[ ]:


# In[ ]:


# In[ ]:


# In[122]:


len(shice_list)

# In[123]:


shice_list

# In[83]:


shice_list = [[[81.1, 4], [310, 5], [87.0, 4], [310, 5], [981, 0], [780, 1], [17.0, 2], [59.0, 3], [92.1, 4], [310, 5]],
              [[71.6, 4], [307, 5], [73.7, 4], [307, 5], [981, 0], [785, 1], [17.0, 2], [58.0, 3], [78.1, 4], [307, 5]]]

# In[ ]:


# In[103]:


biaozhun_list

# In[ ]:


# In[ ]:


# In[ ]:


# In[ ]:


# In[ ]:


# In[ ]:


# In[ ]:


# In[ ]:


# In[ ]:


# In[ ]:


# In[ ]:


# In[ ]:


# In[12]:


import os
import cv2

# In[18]:


path = 'H:\\20201111_dqform\\test\\'

# In[20]:


index = 0
for i in range(1, 6):
    index_imgs = '000' + str(i)
    img_path = path + index_imgs + '\\binary_cell\\'
    img_names = os.listdir(img_path)
    for img in img_names:
        img = cv2.imread(img_path + img)
        cv2.imwrite('H:\\20201111_dqform\\test\\train_roi\\' + str(index) + '.png', img)
        index = index + 1

# In[41]:


i = 0
img_train = os.listdir("H:\\20201111_dqform\\test\\train\\")
for img_name in img_train:
    img = cv2.imread("H:\\20201111_dqform\\test\\train\\" + img_name)
    img = cv2.resize(img, (128, 128))
    # img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # img_threshold = cv2.threshold(img_gray, 100, 255, cv2.THRESH_OTSU)
    # print(img_threshold.shape)
    cv2.imwrite("H:\\20201111_dqform\\test\\data\\images\\" + str(i) + '.png', img)
    i = i + 1

# In[43]:


i = 0
img_train = os.listdir("H:\\20201111_dqform\\test\\data\\images\\")
for img_name in img_train:
    img = cv2.imread("H:\\20201111_dqform\\test\\data\\images\\" + img_name)
    # img = cv2.resize(img, (128, 128))
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, img_threshold = cv2.threshold(img_gray, 100, 255, cv2.THRESH_OTSU)
    # print(img_threshold.shape)
    cv2.imwrite("H:\\20201111_dqform\\test\\data\\images\\" + str(i) + '.png', img_threshold)
    i = i + 1

# In[ ]:


# In[ ]:


# In[70]:


import cv2

# In[78]:


masks = os.listdir("H:\\20201111_dqform\\zifu_roi\\dataset\\mask\\")
img = cv2.imread('H:\\20201111_dqform\\zifu_roi\\dataset\\mask\\' + masks[0])

# In[79]:


img.shape

# In[ ]:


# In[ ]:


# In[83]:


for name in masks:

    img = cv2.imread('H:\\20201111_dqform\\zifu_roi\\dataset\\mask\\' + name)

    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    for i in range(128):
        for j in range(128):
            if (img_gray[i, j]):
                img_gray[i, j] = 255
    cv2.imwrite('H:\\20201111_dqform\\zifu_roi\\dataset\\masks\\' + name, img_gray)

# In[ ]:


# In[67]:


plt.imshow(img)

# In[49]:


"H:\\20201111_dqform\\字符提取\\dataset\\mask\\" + masks[0]

# In[ ]:
